package com.ja.openchat.viewmodels;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;

import com.ja.openchat.BR;
import com.ja.openchat.R;

import java.lang.reflect.Constructor;
import java.util.List;

import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.base.ItemViewModel;
import me.goldze.mvvmhabit.base.MultiItemViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.tatarka.bindingcollectionadapter2.ItemBinding;
import me.tatarka.bindingcollectionadapter2.OnItemBind;

//分页
public abstract class PagedViewModel<T extends ItemViewModel, K> extends BaseViewModel {
    public static final String MULTIRECYCLETYPE_EMPTY = "multirecycletype_empty";
    public static final String MULTIRECYCLETYPE_EMPTY_WRAP = "multirecycletype_empty_wrap";
    public static final String MULTIRECYCLETYPE_CONTENT = "multirecycletype_content";
    public int currentPage = 1;
    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();

    public class UIChangeObservable {
        //下拉刷新完成
        public SingleLiveEvent finishRefreshing = new SingleLiveEvent<>();
        //上拉加载完成
        public SingleLiveEvent finishLoadmore = new SingleLiveEvent<>();
        //是否可以加载更多
        public SingleLiveEvent<Boolean> enableFinishLoadmore = new SingleLiveEvent<>();
    }

    public PagedViewModel(@NonNull Application application) {
        super(application);
    }

    /**
     * 获取条目下标
     *
     * @param netWorkItemViewModel
     * @return
     */
    public int getItemPosition(T netWorkItemViewModel) {
        return observableList.indexOf(netWorkItemViewModel);
    }

    //给RecyclerView添加ObservableList
    public ObservableList<MultiItemViewModel> observableList = new ObservableArrayList<>();
    //下拉刷新
    public BindingCommand onRefreshCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            currentPage = 1;
            requestData(1);
        }
    });
    //上拉加载
    public BindingCommand onLoadMoreCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            requestData(currentPage);
        }
    });

    public boolean showEmptyWrap() {
        return false;
    }

    public abstract void requestData(int page);

    public void finishRefreshAndLoad(int page, List<K> objects, Class<T> t) {
        //请求刷新完成收回
        if (page == 1) {
            observableList.clear();
            addData(objects, t);
            if (showEmpty())
                if (objects == null || objects.size() == 0) {
                    EmptyViewModel emptyViewModel = new EmptyViewModel(this, "暂无数据");
                    if (showEmptyWrap()) {
                        emptyViewModel.multiItemType(MULTIRECYCLETYPE_EMPTY_WRAP);
                    } else {
                        emptyViewModel.multiItemType(MULTIRECYCLETYPE_EMPTY);
                    }
                    observableList.add(emptyViewModel);
                }
            uc.finishRefreshing.call();
        } else {
            uc.finishLoadmore.call();
            addData(objects, t);
        }
        if (objects == null || objects.size() < PAGE_COUNT()) {
            uc.enableFinishLoadmore.setValue(false);
        } else {
            uc.enableFinishLoadmore.setValue(true);
        }
    }

    public int PAGE_COUNT() {
        return 20;
    }

    public boolean showEmpty() {
        return true;
    }

    public void addData(List<K> objects, Class<T> t) {
        if (objects != null && objects.size() > 0) {
            currentPage++;
            for (K itemsEntity : objects) {
                //双向绑定动态添加Item
                try {
                    T o = newInstance(t.getName(), new Object[]{this, itemsEntity});
                    if (o instanceof MultiItemViewModel) {
                        ((MultiItemViewModel<?>) o).multiItemType(MULTIRECYCLETYPE_CONTENT);
                    }
                    observableList.add((MultiItemViewModel) o);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private T newInstance(String className, Object[] args) throws Exception {
        Class newoneClass = Class.forName(className);
        Class[] argsClass = new Class[args.length];
        for (int i = 0, j = args.length; i < j; i++) {
            argsClass[i] = args[i].getClass();
        }
        Constructor cons = newoneClass.getConstructor(argsClass);
        return (T) cons.newInstance(args);
    }


    public ItemBinding<MultiItemViewModel> itemBinding = ItemBinding.of(new OnItemBind<MultiItemViewModel>() {
        @Override
        public void onItemBind(ItemBinding itemBinding, int position, MultiItemViewModel item) {
            //通过item的类型, 动态设置Item加载的布局
            String itemType = (String) item.getItemType();
            if (MULTIRECYCLETYPE_CONTENT.equals(itemType)) {
                //设置通用布局
                itemBinding.set(BR.viewModel, initContentView());
            } else if (MULTIRECYCLETYPE_EMPTY_WRAP.equals(itemType)) {
                //设置空数据布局
                itemBinding.set(BR.viewModel, R.layout.item_multi_empty_wrap);
            } else if (MULTIRECYCLETYPE_EMPTY.equals(itemType)) {
                //设置空数据布局
                itemBinding.set(BR.viewModel, R.layout.item_multi_empty);
            } else {
                onMutilItemBind(itemBinding, position, item);
            }
        }
    });

    public void onMutilItemBind(ItemBinding itemBinding, int position, MultiItemViewModel item) {
    }

    public abstract int initContentView();
}
